/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.mall.util.jsp.ImportTag
   Module Description   :

   Date Created      : 2010/1/7
   Original Author   : andy.chuang
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.mall.util.jsp;

import java.io.File;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.yaodian100.core.cache.exception.CacheException;
import com.yaodian100.core.cache.service.CacheService;
import com.yaodian100.core.common.utils.FileUtils;
import com.yaodian100.core.common.utils.ServerValue;

/**
 * @author andy.chuang
 * 
 */
public class StaticImportTag extends BodyTagSupport {

	/**
     * 
     */
	private static final long serialVersionUID = 3682690788219329700L;
	private static Logger LOGGER = LoggerFactory.getLogger(StaticImportTag.class);
	private String path;

	/**
	 * @return the path
	 */
	public String getPath() {
		return path;
	}

	/**
	 * @param path the path to set
	 */
	public void setPath(String path) {
		this.path = path;
	}

	@Override
	public int doStartTag() throws JspException {
		return EVAL_BODY_BUFFERED;
	}

	@Override
	public int doAfterBody() throws JspException {
		return EVAL_BODY_INCLUDE;
	}

	@Override
	public int doEndTag() throws JspException {
		try {
			File file = new File(path);

			ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());
			CacheService<String> staticPage = (CacheService<String>) ctx.getBean("staticPageCache");

			if (ServerValue.isStaticPageCache()) {
				// 如果使用 cache
				if (staticPage != null) {
					// 而且 cache 存在
					try {
						String body = staticPage.get(path);
						// cache 到, 将资料输出
						pageContext.getOut().print(body);
					} catch (CacheException e) {
						// 没有 cache 到, 更新 cache 资讯
						String body = FileUtils.readFileToString(file);
						pageContext.getOut().print(body);
						staticPage.put(path, body);
					}
				}
			} else {
				// 没有使用 cache
				String body = FileUtils.readFileToString(file);
				pageContext.getOut().print(body);
			}
		} catch (Exception e) {
			LOGGER.warn("display static html failed!!html abs path:" + path);
		}

		return EVAL_PAGE;
	}
}
